from django.shortcuts import render, HttpResponse,redirect
from app02.My_forms import EmpForm
from app02 import models
from django.core.exceptions import ValidationError
# Create your views here.

def add_emp2(request):
    if request.method == "GET":
        form = EmpForm()  # 初始化form对象
        return render(request, "addemp2.html", {"form":form})
    else:
        form = EmpForm(request.POST)  # 将数据传给form对象
        if form.is_valid():  # 进行校验
            data = form.cleaned_data
            data.pop("r_salary")
            models.Emp.objects.create(**data)
            return redirect("/")
        else:  # 校验失败
            clear_errors = form.errors.get("__all__")  # 获取全局钩子错误信息
            return render(request, "addemp2.html", {"form": form, "clear_errors": clear_errors})



def add_emp(request):
    if request.method == "GET":
        form = EmpForm()
        return render(request, "addemp.html", {"form": form})
    else:
        form = EmpForm(request.POST)
        print('收到：',request.POST['name'])
        if form.is_valid():  # 进行数据校验
            # 校验成功
            data = form.cleaned_data  # 校验成功的值，会放在cleaned_data里。
            # data.pop('salary')
            print(data)

            models.Emp.objects.create(**data)
            return HttpResponse(
                'ok'
            )
            # return render(request, "add_emp.html", {"form": form})
        else:
            print(form.errors)    # 打印错误信息
            clean_errors = form.errors.get("__all__")
            print(222, clean_errors)
        return render(request, "addemp.html", {"form": form, "clean_errors": clean_errors})
